<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\AndroidVersion;
use App\Models\AppBanner;
use App\Models\FeedBack;
use App\Models\News;
use App\Models\NewsData;
use App\Models\School;
use Illuminate\Http\Request;
use App\Jobs\SendRegisterEmail;
use Tymon\JWTAuth\Facades\JWTAuth;
use App\Repositories\NewsRepository;
use App\Repositories\HandBookRepository;
use App\Repositories\SimulatBookRepository;
use App\Transformers\UserTransformer;

class PublicController extends BaseController
{


    protected $news;
    protected $handBook;
    protected $simulatbook;
    public function __construct(
        NewsRepository $news,
        HandBookRepository $handBook,
        SimulatBookRepository $simulatbook
    )
    {
        $this->news = $news;
        $this->handBook = $handBook;
        $this->simulatbook = $simulatbook;
    }

    /**
     * @api {get} /public/banner 获取banner图片
     * @apiDescription 首页banner
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/banner
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "",
     *       "code": 200,
     *       "data": [
     *          {
     *              "id": banner ID,
     *              "imgurl" :  "图片路径需要加上域名"
     *          }
     *      ]
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function appbanner()
    {
        //获取banner图片
        $banner = AppBanner::get();

        return $this->successResponse('success', ['data' => $banner]);
    }


    /**
     * @api {post} /public/feedback 意见反馈
     * @apiDescription 首页banner
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/feedback
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {String} [content]  反馈内容
     *
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "操作成功",
     *       "code": 200
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function feedback(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        $content = $request->input('content');

        if (!$content) {
            return $this->errorResponse('参数错误');
        }

        $feedback['userid'] = $user->item_id;
        $feedback['content'] = $content;
        $feedback['createtime'] = time();
        $feedback['school_id'] = $user->item->school_id;

        $rs = FeedBack::insert($feedback);

        if ($rs) {
            return $this->successResponse('操作成功');
        }

        return $this->errorResponse('操作失败');
    }


    /**
     * @api {get} /public/feedbackList 意见反馈列表
     * @apiDescription 意见反馈列表
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/feedbackList
     * @apiHeader {String} Authorization 用户旧的jwt-token, value 以 Bearer 开头
     * @apiParam {Int} [page]  第几页默认1
     * @apiParam {Int} [size]  条数
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "操作成功",
     *       "code": 200
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function feedbackList(Request $request)
    {
        $user = JWTAuth::parseToken()->authenticate();//验证token

        $page = $request->input('page', 1);
        $size = $request->input('size', 15);

        if($user->item instanceof School){
            $rs = FeedBack::leftJoin('students', 'feedback.userid', '=', 'students.id')
                            ->select('feedback.*', 'students.name', 'students.photo')
                            ->where('feedback.school_id', $user->item_id)
                            ->limit($size)->offset(($page - 1) * $size)->orderBy('id','desc')->get();
        }else{
            $rs = FeedBack::leftJoin('students', 'feedback.userid', '=', 'students.id')
                            ->select('feedback.*', 'students.name', 'students.photo')
                            ->where('feedback.userid', $user->item_id)
                            ->limit($size)->offset(($page - 1) * $size)->orderBy('id','desc')->get();
        }

        return $this->successResponse('操作成功', ['data' => $rs]);
    }


    /**
     * @api {post} /public/news 资讯热点
     * @apiDescription 首页banner
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/news
     * @apiParam {Number} [page]  page
     * @apiParam {Number} [size]  size
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "操作成功",
     *       "code": 200
     *       "data": [
     *          {
                    "id": 591,
                    "catid": 16,
                    "typeid": 0,
                    "title": "开车不系安全带该怎么处罚",
                    "style": "",
                    "thumb": "/attachment/file/content/2016/06/574e4cb2dded7.jpg",
                    "keywords": "",
                    "tags": "",
                    "description": "　　开车不系安全带是一件很危险的事情，一旦发生交通事故很容易出现人员的伤亡。并且现在一旦不系安全带被查到，将会受到处罚。　　不系安全带处罚标准不系安全带扣3分处罚100元罚款，副驾驶不系安全带的扣司机1分，罚款50元。还有就是开车时，抽烟记1分，罚款100元。这些规定对驾车行车安全提供了很大的保障，对自身安全也有很大的保障，别看这些是小事情，不按照规定去做的话，出现事故后，按照要求做的，自身伤害回减速很多。不...",
                    "posid": 0,
                    "url": "/index.php?a=shows&catid=16&id=591",
                    "listorder": 0,
                    "status": 99,
                    "sysadd": 1,
                    "islink": 0,
                    "username": "admin",
                    "inputtime": 1464749144,
                    "updatetime": 1464749144,
                    "views": 6,
                    "yesterdayviews": 0,
                    "dayviews": 1,
                    "weekviews": 1,
                    "monthviews": 1,
                    "viewsupdatetime": 1496941415
                    },
     *       ]
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function news(Request $request)
    {
        $param = [
            'page' => $request->input('page', 1),
        ];

        $size = $request->input('size', 10);

        $data = $this->news->index($param, '', $size);

        if(count($data)){
            foreach($data as $v){
                $n_d = NewsData::find($v->id);
                $v->content =  $n_d ?  str_replace('<img src="','<img src="http://www.exc360.com',$n_d->content) : '';
            }
        }

        return $this->successResponse('success', ['data'=>$data ? $data : []]);
    }


    /**
     * @api {post} /public/handBook 学车助理
     * @apiDescription 学车助理
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/handBook
     * @apiParam {Number} [page]  page
     * @apiParam {Number} [size]  size
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "操作成功",
     *       "code": 200
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function handBook(Request $request)
    {

        $param = [
            'page' => $request->input('page', 1),
        ];

        $size = $request->input('size',10);

        $data['list'] = $this->handBook->index($param, '', $size);
        $data['service_phone'] = '';
        return $this->successResponse('success', ['data' => $data]);
    }


    /**
     * @api {get} /public/simulatbook 驾考攻略
     * @apiDescription 驾考攻略
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/simulatbook
     * @apiParam {Number} [page]  page
     * @apiParam {Number} [size]  size
     * @apiParam {Number} [km]  km
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "操作成功",
     *       "code": 200
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function simulatbook(Request $request)
    {

        $param = [
            'page' => $request->input('page', 1),
            'km' => $request->input('km')
        ];

        $size = $request->input('size',10);

        $data['list'] = $this->simulatbook->index($param, '', $size);
        return $this->successResponse('success', ['data' => $data]);
    }



    /**
     * @api {get} /public/updateAndroid 安卓更新检测
     * @apiDescription 驾考攻略
     * @apiGroup Public
     * @apiPermission none
     * @apiSampleRequest /api/public/updateAndroid
     * @apiVersion 1.0.0
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 201 Created
     *   {
     *       "message": "操作成功",
     *       "code": 200
     *   }
     * @apiErrorExample {json} Error-Response:
     *     HTTP/1.1 404 Not Found
     *     {
     *       "error": "UserNotFound"
     *     }
     */
    public function updateAndroid(Request $request)
    {

        $version = AndroidVersion::orderBy('id', 'desc')->first();

        return $this->successResponse('success',['data' => $version ? $version : []]);
    }

}
